/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.eclass.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
import javax.imageio.ImageIO;
import javax.servlet.annotation.WebServlet;

/**
 *
 * @author fortruth
 */
@WebServlet("/verify")
public class Verify extends ActionFace {

    public void doCreateVerifi() {
        BufferedImage img = new BufferedImage(68, 22, BufferedImage.TYPE_INT_RGB);

        Graphics g = img.getGraphics(); // 得到该图片的绘图对象
        Random r = new Random();
        Color c = new Color(200, 150, 255);
        g.setColor(c);

        g.fillRect(0, 0, 68, 22); // 填充整个图片的颜色

        StringBuilder theVerify = new StringBuilder();  // //random characters; 4 length;

        char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toCharArray();
        int index, len = ch.length;

        for (int i = 0; i < 4; i++) {
            index = r.nextInt(len);
            g.setColor(new Color(r.nextInt(88), r.nextInt(188), r.nextInt(255)));
            g.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 22));// 输出的字体和大小      
            g.drawString("" + ch[index], (i * 15) + 3, 18);//写什么数字，在图片的什么位置画
            theVerify.append(ch[index]);
        }

        request.getSession().setAttribute("verify", theVerify.toString());
        try {
            response.reset();//fix for the error report " getWriter() has already been called for this response"
            ImageIO.write(img, "PNG", response.getOutputStream());
        } catch (IOException ex) {
            logger.error(ex);
        }

        session.setAttribute("verify", theVerify);
    }

    public void doCheckverify() {
        String verified = request.getParameter("verify");
        logger.info(verified);
        logger.info(session.getAttribute("verify"));
        if (!verified.equalsIgnoreCase(session.getAttribute("verify").toString())) {
            echoAjaxError("");
        }
    }

    @Override
    public void doIndex() {
        this.doCreateVerifi();
    }
}
